//
// Copyright (C) [2024] Xingyun Integrated Circuit, Inc.
//
// GreenCode was a private technology asset of Xingyun Integrated Circuit， Inc （Confidential）
//  Author: Shawn.Tan
//  Date : 2025.10.28
//
//  History : Initial Version 2025.10.28
//
//
#include "ThreadContext.h"

#include "pybind11/pybind11.h"

#include "ThreadDispatcher.h"

/*!
  \file ThreadContext.cc
  \brief Code supporting providing a scoped call guard for multithreaded access.
*/

namespace py = pybind11;

namespace Green {

  ThreadContext::ThreadContext()
  {
    // Must release the GIL prior to calling a C++ method that may block such as the call to
    // Request() below
    py::gil_scoped_release release;

    ThreadDispatcher* dispatcher = ThreadDispatcher::GetCurrentDispatcher();
    dispatcher->Request();
  }

  ThreadContext::~ThreadContext()
  {
    ThreadDispatcher* dispatcher = ThreadDispatcher::GetCurrentDispatcher();
    dispatcher->Finish();
  }

  uint32 ThreadContext::GetThreadId() const
  {
    ThreadDispatcher* dispatcher = ThreadDispatcher::GetCurrentDispatcher();
    return dispatcher->GetThreadId();
  }

  ThreadContextNoAdvance::ThreadContextNoAdvance()
  {
    // Must release the GIL prior to calling a C++ method that may block such as the call to
    // Request() below
    py::gil_scoped_release release;

    ThreadDispatcher* dispatcher = ThreadDispatcher::GetCurrentDispatcher();
    dispatcher->Request();
  }

  // The call to FinishNoAdvance() will maintain the current thread, avoiding a forced context
  // switch. This should be far more performant than the Finish() call in ThreadContext, but isn't
  // appropriate for cases where we want to advance to the next thread.
  ThreadContextNoAdvance::~ThreadContextNoAdvance()
  {
    ThreadDispatcher* dispatcher = ThreadDispatcher::GetCurrentDispatcher();
    dispatcher->FinishNoAdvance();
  }

  uint32 ThreadContextNoAdvance::GetThreadId() const
  {
    ThreadDispatcher* dispatcher = ThreadDispatcher::GetCurrentDispatcher();
    return dispatcher->GetThreadId();
  }

}
